/*
 * Copyright© 2003-2019 浙江汇信科技有限公司, All Rights Reserved.
 */
package com.icinfo.cloud.provider.punish.ucase.casemain.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.icinfo.cloud.common.security.util.UserUtil;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.common.utils.BaseUtil;
import com.icinfo.cloud.provider.common.utils.SMSUtils;
import com.icinfo.cloud.provider.peripheralinterface.xzzf.service.IXzzfInterfaceService;
import com.icinfo.cloud.provider.peripheralinterface.xzzf.vo.ZfAndManageUserInfoVO;
import com.icinfo.cloud.provider.punish.common.caseregister.service.IRegisterCommonService;
import com.icinfo.cloud.provider.punish.common.datareport.enums.CaseChangeOperationTypeEnum;
import com.icinfo.cloud.provider.punish.common.datareport.service.ICaseDataChangeReportRecordService;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.CaseStatusEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.CaseTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseHandlePersonAdjustInfoService;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseHandlePersonRecordService;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseInfoAdjustRecordService;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICasePartiesRecordService;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.*;
import com.icinfo.cloud.provider.punish.ucase.caseregister.dto.CaseHandlePersonInfoDto;
import com.icinfo.cloud.xzcf.provider.member.userinfo.dto.UserDTO;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import com.icinfo.framework.mybatis.pagehelper.PageHelper;
import com.icinfo.framework.tools.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 描述: 案件承办人调整明细表 case_handle_person_adjust_info 对应的Service接口实现类.<br>
 *
 * @author framework generator
 * @date 2022年10月14日
 */
@Service
public class CaseHandlePersonAdjustInfoServiceImpl extends MyBatisServiceSupport implements ICaseHandlePersonAdjustInfoService {
    /**
     * 日志记录器
     */
    private static final Logger logger = LoggerFactory.getLogger(CaseHandlePersonAdjustInfoServiceImpl.class);

    @Autowired
    private CaseHandlePersonAdjustInfoMapper caseHandlePersonAdjustInfoMapper;
    @Resource
    private CaseHandlePersonRecordMapper caseHandlePersonRecordMapper;
    @Resource
    private ICasePartiesRecordService casePartiesRecordService;
    @Resource
    private ICaseHandlePersonRecordService caseHandlePersonRecordService;
    @Resource
    private ICaseInfoAdjustRecordService caseInfoAdjustRecordService;
    @Resource
    private CaseInfoAdjustRecordMapper caseInfoAdjustRecordMapper;
    @Resource
    private IXzzfInterfaceService xzzfInterfaceService;
    @Value("${isCheckHandleSign}")
    private String isCheckHandleSign;
    @Resource
    private IRegisterCommonService commonService;
    @Resource
    private CasePartiesRecordMapper casePartiesRecordMapper;
    @Resource
    private CaseMainInfoMapper caseMainInfoMapper;
    @Resource
    private CaseAppendixRecordMapper caseAppendixRecordMapper;
    @Value("${ding.sendUrl}")
    private String dingSendUrl;
    @Resource
    private CaseDocumentRecordMapper caseDocumentRecordMapper;
    @Resource
    private ICaseDataChangeReportRecordService caseDataChangeReportRecordService;


    /**
     * 调整记录列表
     * @author liyafeng
     * @date 2022/10/14
      * @param request
     * @return {@link List< CaseHandlePersonAjustInfoVo>}
     */
    @Override
    public List<CaseHandlePersonAjustInfoVo> getCaseHandlePersonAdjustInfoPageList(CaseHandlePersonAdjustInfoPageRequest request) {
        UserDTO userDTO= UserUtil.getUserInfo();
        String deptType=userDTO.getDeptType();
        if(Constant.STRING_2.equals(deptType)){
            request.setCaseDeptCode(userDTO.getDeptCode());
        }
        request.setCaseOrgCode(userDTO.getOrgCode());
        PageHelper.startPage(request.getPageNum(), request.getLength());
        List<CaseHandlePersonAjustInfoVo> caseHandlePersonAjustInfoVoList=caseHandlePersonAdjustInfoMapper.selectCaseHandlePersonAdjustInfoPageList(request);
        for (CaseHandlePersonAjustInfoVo vo:caseHandlePersonAjustInfoVoList) {
            vo.setCaseStatusName(CaseStatusEnum.getValueByCode(vo.getCaseStatus()));
            String partyName=getPartyName(vo.getCaseId());
            vo.setPartyName(partyName);
        }
        return caseHandlePersonAjustInfoVoList;
    }
    /**
     * 获取当事人名称
     * @author liyafeng
     * @date 2022/10/19
      * @param caseId
     * @return {@link String}
     */
    public String getPartyName(String caseId) {
        String partyName="";
        //当事人名称处理
        List<CasePartiesRecordVo> partiesRecords = getCasePartiesInfo(caseId);
        if (!ObjectUtils.isEmpty(partiesRecords)) {
            if (partiesRecords.size() > 1) {
                partyName= partiesRecords.get(0).getPartyName() + "等" + partiesRecords.size() + "个当事人";
            } else {
                partyName=partiesRecords.get(0).getPartyName();
            }
        }
        return partyName;
    }

    /**
     * 案件列表
     * @author liyafeng
     * @date 2022/10/18
      * @param request
     * @return {@link List< HandleAdjustCaseInfoVo>}
     */
    @Override
    public List<HandleAdjustCaseInfoVo> getHandleAdjustCaseInfoPageList(HandleAdjustCaseInfoPageRequest request) {
        PageHelper.startPage(request.getPageNum(), request.getLength());
        UserDTO userDTO= UserUtil.getUserInfo();
        String deptType=userDTO.getDeptType();
        if(Constant.STRING_2.equals(deptType)){
            request.setCaseDeptCode(userDTO.getDeptCode());
        }
        request.setCaseOrgCode(userDTO.getOrgCode());
        //根据casePartyType组装参数
        getPartyTypeParam(request);
        List<HandleAdjustCaseInfoVo> handleAdjustCaseInfoVoList=caseHandlePersonAdjustInfoMapper.selectHandleAdjustCaseInfoVoPageList(request);
        for (HandleAdjustCaseInfoVo vo:handleAdjustCaseInfoVoList) {
            vo.setCaseStatusName(CaseStatusEnum.getValueByCode(vo.getCaseStatus()));
            vo.setCaseType(CaseTypeEnum.getValueByCode(vo.getCaseType()));
            //查询承办人
            String caseId = vo.getCaseId();
            //1.循环设置处理人员
            Example example = new Example(CaseHandlePersonRecord.class);
            example.createCriteria().andEqualTo("caseId", caseId).andEqualTo("status",Constant.STRING_1);
            example.orderBy("handlePersonType").asc();
            List<CaseHandlePersonRecord> handlePersonRecords = caseHandlePersonRecordMapper.selectByExample(example);
            String handPersonName = handlePersonRecords.stream().map(p -> p.getHandlePersonName()).collect(Collectors.joining(","));
            vo.setCaseHandleName(handPersonName);
            String partyName=getPartyName(vo.getCaseId());
            vo.setPartyName(partyName);
        }
        return handleAdjustCaseInfoVoList;
    }

    private void getPartyTypeParam(HandleAdjustCaseInfoPageRequest request) {
        if(Constant.STRING_1.equals(request.getCasePartyType())){
            //个人 类型大类为 1  类型小类 1
            request.setCasePartyBigType(Constant.STRING_1);
            request.setCasePartyType(Constant.STRING_1);
        }else if(Constant.STRING_2.equals(request.getCasePartyType())){
            //法人 类型大类为 2  类型小类 1
            request.setCasePartyBigType(Constant.STRING_2);
            request.setCasePartyType(Constant.STRING_1);
        }else if(Constant.STRING_3.equals(request.getCasePartyType())){
            //个体工商户 类型大类为 2  类型小类 2
            request.setCasePartyBigType(Constant.STRING_2);
            request.setCasePartyType(Constant.STRING_2);
        }else if(Constant.STRING_4.equals(request.getCasePartyType())){
            //其他组织 类型大类为 2  类型小类 2
            request.setCasePartyBigType(Constant.STRING_2);
            request.setCasePartyType(Constant.STRING_3);

        }
    }

    /**
     * 获取当事人
     * @author liyafeng
     * @date 2022/10/19
      * @param caseId
     * @return {@link List< CasePartiesRecordVo>}
     */
    public List<CasePartiesRecordVo> getCasePartiesInfo(String caseId) {
        Example queryExample = new Example(CasePartiesRecord.class);
        queryExample.createCriteria().andEqualTo("caseId", caseId).andEqualTo("status",Constant.STRING_1);
        queryExample.setOrderByClause(" party_type desc,create_time asc ");
        List<CasePartiesRecord> casePartiesRecord = casePartiesRecordMapper.selectByExample(queryExample);
        List<CasePartiesRecordVo> parties = new ArrayList<>();
        if (ObjectUtils.isEmpty(casePartiesRecord) || casePartiesRecord.size() == 0) {
            return parties;
        } else {
            casePartiesRecord.forEach(e -> {
                CasePartiesRecordVo party = new CasePartiesRecordVo();
                BeanUtils.copyProperties(e, party);
                parties.add(party);
            });
            return parties;
        }
    }
    /**
     * 调整明细
     * @author liyafeng
     * @date 2022/10/18
      * @param dto
     * @return {@link CaseHandlePersonAjustInfoDetailVo}
     */
    @Override
    public CaseHandlePersonAjustInfoDetailVo getCaseHandlePersonAdjustInfoDetail(HandlePersonAdjustInfoDto dto) {
        //如果调整记录id 为空
        /*//查询当前承办人
        CaseHandlePersonAjustInfoDetailVo vo=new CaseHandlePersonAjustInfoDetailVo();
        List<CaseHandlePersonRecord> nowHandlePersons = caseHandlePersonRecordService.getCaseHandlePersonRecordList(dto.getCaseId());
        List<CaseHandlePersonInfoDto> handlePersonInfoList = new ArrayList<>();
        for (CaseHandlePersonRecord personRecord : nowHandlePersons) {
            CaseHandlePersonInfoDto handlePersonInfoDto = new CaseHandlePersonInfoDto();
            BeanUtils.copyProperties(personRecord, handlePersonInfoDto);
            handlePersonInfoList.add(handlePersonInfoDto);
        }
        //查询历史承办人
        List<CaseHandlePersonInfoDto> beforeHandlePersonInfoList = new ArrayList<>();
        List<CaseHandlePersonRecord> handlePersonRecordInvalidList=caseHandlePersonRecordMapper.selectHandlePersonRecordInvalidListByCaseId(dto.getCaseId());
        for (CaseHandlePersonRecord personRecord : handlePersonRecordInvalidList) {
            CaseHandlePersonInfoDto handlePersonInfoDto = new CaseHandlePersonInfoDto();
            BeanUtils.copyProperties(personRecord, handlePersonInfoDto);
            beforeHandlePersonInfoList.add(handlePersonInfoDto);
        }*/
        CaseHandlePersonAjustInfoDetailVo vo=new CaseHandlePersonAjustInfoDetailVo();
        vo.setCaseId(dto.getCaseId());
        List<CaseHandlePersonInfoDto> handlePersonInfoList = new ArrayList<>();
        List<CaseHandlePersonInfoDto> beforeHandlePersonInfoList = new ArrayList<>();
        CaseInfoAdjustRecord caseInfoAdjustRecord=new CaseInfoAdjustRecord();
        List<AppendixDto> appendixList = new ArrayList<>();
        if(StringUtils.isNotBlank(dto.getId())){
            //id不为空的话 根据调整记录id查询
            //根据id查询调整记录
            CaseHandlePersonAdjustInfo caseHandlePersonAdjustInfo=caseHandlePersonAdjustInfoMapper.selectByPrimaryKey(dto.getId());
            String adjustAfterHandlerId=caseHandlePersonAdjustInfo.getAdjustAfterHandlerId();
            String adjustBeforeHandlerId=caseHandlePersonAdjustInfo.getAdjustBeforeHandlerId();
            handlePersonInfoList=getHandlePersonInfoListByAdjustHandlerId(adjustAfterHandlerId,dto.getCaseId());
            beforeHandlePersonInfoList=getHandlePersonInfoListByAdjustHandlerId(adjustBeforeHandlerId,dto.getCaseId());
            caseInfoAdjustRecord=caseInfoAdjustRecordMapper.selectByPrimaryKey(caseHandlePersonAdjustInfo.getRecordId());
        }else{
            //id为空的话 根据caseid查询最新的调整明细
            List<CaseHandlePersonRecord> nowHandlePersons = caseHandlePersonRecordService.getCaseHandlePersonRecordList(dto.getCaseId());
            for (CaseHandlePersonRecord personRecord : nowHandlePersons) {
                CaseHandlePersonInfoDto handlePersonInfoDto = new CaseHandlePersonInfoDto();
                BeanUtils.copyProperties(personRecord, handlePersonInfoDto);
                handlePersonInfoList.add(handlePersonInfoDto);
            }
            List<CaseHandlePersonRecord> handlePersonRecordInvalidList=caseHandlePersonRecordMapper.selectHandlePersonRecordInvalidListByCaseId(dto.getCaseId());
            for (CaseHandlePersonRecord personRecord : handlePersonRecordInvalidList) {
                CaseHandlePersonInfoDto handlePersonInfoDto = new CaseHandlePersonInfoDto();
                BeanUtils.copyProperties(personRecord, handlePersonInfoDto);
                beforeHandlePersonInfoList.add(handlePersonInfoDto);
            }
            //查询调整记录表
            List<CaseInfoAdjustRecord> caseInfoAdjustRecordList=caseInfoAdjustRecordMapper.selectCaseHandlePersonAdjustRecord(dto.getCaseId());
            if(!ObjectUtils.isEmpty(caseInfoAdjustRecordList)) {
                caseInfoAdjustRecord = caseInfoAdjustRecordList.get(0);
            }
        }
        vo.setAfterHandlePersonInfoList(handlePersonInfoList);
        vo.setBeforeHandlePersonInfoList(beforeHandlePersonInfoList);
        if(null!=caseInfoAdjustRecord){
            vo.setAdjustReason(caseInfoAdjustRecord.getAdjustReason());
            vo.setAdjustReasonType(caseInfoAdjustRecord.getAdjustReasonType());
            if(StringUtils.isNotBlank(caseInfoAdjustRecord.getAttachmentId())) {
                List<String> appendIdList = Arrays.asList(caseInfoAdjustRecord.getAttachmentId().split(","));
                if (!ObjectUtils.isEmpty(appendIdList)) {
                    for (String id : appendIdList) {
                        AppendixDto appendixDto = new AppendixDto();
                        CaseAppendixRecord caseAppendixRecord = caseAppendixRecordMapper.selectByPrimaryKey(id);
                        BeanUtils.copyProperties(caseAppendixRecord, appendixDto);
                        appendixList.add(appendixDto);
                    }
                }
            }
            vo.setAppendixList(appendixList);
        }
        return vo;
    }
    /**
     * 根据承办人id查询主办 协办列表
     * @author liyafeng
     * @date 2022/10/22
      * @param adjustHandlerId
     * @return {@link List< CaseHandlePersonInfoDto>}
     */
    private List<CaseHandlePersonInfoDto> getHandlePersonInfoListByAdjustHandlerId(String adjustHandlerId,String caseId) {
        List<CaseHandlePersonInfoDto> caseHandlePersonInfoDtoList=new ArrayList<>();
        if(StringUtils.isNotBlank(adjustHandlerId)){
            List<String> afterHandlePersonIds=Arrays.asList(adjustHandlerId.split(","));
            /*for (String afterHandlePersonId:AfterHandlePersonIds) {
                CaseHandlePersonRecord personRecord=caseHandlePersonRecordMapper.selectByPrimaryKey(afterHandlePersonId);
                CaseHandlePersonInfoDto handlePersonInfoDto = new CaseHandlePersonInfoDto();
                BeanUtils.copyProperties(personRecord, handlePersonInfoDto);
                caseHandlePersonInfoDtoList.add(handlePersonInfoDto);
            }*/
            if(!ObjectUtils.isEmpty(afterHandlePersonIds)&&afterHandlePersonIds.size()==2){
                for(int i=0;i<Constant.INTEGER_2;i++){
                    Example example=new Example(CaseHandlePersonRecord.class);
                    example.createCriteria().andEqualTo("caseId",caseId).andEqualTo("handlePersonId",afterHandlePersonIds.get(i));
                    List<CaseHandlePersonRecord> caseHandlePersonRecords=caseHandlePersonRecordMapper.selectByExample(example);
                    if(!ObjectUtils.isEmpty(caseHandlePersonRecords)){
                        CaseHandlePersonInfoDto handlePersonInfoDto = new CaseHandlePersonInfoDto();
                        BeanUtils.copyProperties(caseHandlePersonRecords.get(0), handlePersonInfoDto);
                        handlePersonInfoDto.setHandlePersonType(String.valueOf(i+1));
                        caseHandlePersonInfoDtoList.add(handlePersonInfoDto);
                    }
                }
            }
        }
        return caseHandlePersonInfoDtoList;
    }

    /**
     * 调整承办人员
     * @author liyafeng
     * @date 2022/10/18
      * @param dto
     * @return {@link int}
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addCaseHandlePersonAdjustInfo(HandlePersonAdjustInfoAddDto dto) {
        //校验是否有 审批中状态文书
        List<String> recordIds=caseDocumentRecordMapper.selectCaseDocumentRecordContainPendingList(dto.getCaseId());
        if(!ObjectUtils.isEmpty(recordIds)){
            throw new BusinessException("当前案件有审批中的文书，请先完成审批，再调整当事人");
        }
        UserDTO userDTO=UserUtil.getUserInfo();
        int num=0;
        //查询原有办案人员
        List<CaseHandlePersonRecord> oldHandlePersons = caseHandlePersonRecordService.getCaseHandlePersonRecordList(dto.getCaseId());
        List<CaseHandlePersonInfoDto> oldHandlePersonInoldfoList = new ArrayList<>();
        for (CaseHandlePersonRecord personRecord : oldHandlePersons) {
            CaseHandlePersonInfoDto handlePersonInfoDto = new CaseHandlePersonInfoDto();
            BeanUtils.copyProperties(personRecord, handlePersonInfoDto);
            oldHandlePersonInoldfoList.add(handlePersonInfoDto);
        }
        //无效原有办案人员
        caseHandlePersonRecordMapper.updateCaseHandlePersonRecordStatusByCaseId(dto.getCaseId());
        //保存附件
        String attachmentId=saveAppendixList(dto,userDTO);
        //新增办案人员
        List<CaseHandlePersonInfoDto> afterHandlePersonInfoList =dto.getAfterHandlePersonInfoList();
        dealCaseRegisterHandlePersonInfo(dto.getAfterHandlePersonInfoList(),dto.getCaseId(),userDTO);
        //新增调整记录与新增调整信息
        num=saveCaseInfoAdjustRecordAndInfo(dto,oldHandlePersonInoldfoList,userDTO,attachmentId);
        try {
            //发送短信跟钉消息-msgType  1 调整后,2 调整前
            sendPhoneMsgAndDingMessage(afterHandlePersonInfoList,dto.getCaseId(),Constant.STRING_1);
            //发送短信跟钉消息-msgType  1 调整后,2 调整前
            sendPhoneMsgAndDingMessage(oldHandlePersonInoldfoList,dto.getCaseId(),Constant.STRING_2);
        }catch (Exception e){
            //消息发送异常 直接跳过
            e.printStackTrace();
        }
        //当事人更新成功后，生成一条记录，然后定时重新上报已经上报成功的数据
        String userId = "";
        if(userDTO != null){
            userId = String.valueOf(userDTO.getUserId());
        }
        caseDataChangeReportRecordService.save(dto.getCaseId(), CaseChangeOperationTypeEnum.OPERATION_TYPE_3.getCode(), userId);
        return num;
    }
    /**
     * 校验是否有文书在审批中
     * @author liyafeng
     * @date 2022/10/24
      * @param dto
     * @return {@link int}
     */
    @Override
    public int checkIsExistDocumentIsApproval(HandlePersonAdjustInfoDto dto) {
        //校验是否有 审批中状态文书
        List<String> recordIds=caseDocumentRecordMapper.selectCaseDocumentRecordContainPendingList(dto.getCaseId());
        if(null!=recordIds&&recordIds.size()>0){
            return recordIds.size();
        }
        return 0;
    }

    /**
     * 发送短信与ding消息
     * @author liyafeng
     * @date 2022/10/20
      * @param handlePersonInfoList
     * @param caseId
     * @param msgType
     * @return
     */
    private void sendPhoneMsgAndDingMessage(List<CaseHandlePersonInfoDto> handlePersonInfoList, String caseId, String msgType) {
        //获取执法人员信息 手机号、浙政钉id
        List<String> afterUserIdList=new ArrayList<>();
        if(!ObjectUtils.isEmpty(handlePersonInfoList)){
            handlePersonInfoList.forEach(e -> {
                afterUserIdList.add(e.getHandlePersonId());
            });
        }
        List<ZfAndManageUserInfoVO> zfAndManageUserInfoVoList = xzzfInterfaceService.getZfAndManageUsersByUserIds(afterUserIdList);
        CaseMainInfoVo caseMainInfoVo=caseMainInfoMapper.selectCaseMainInfo(caseId);
        if(!ObjectUtils.isEmpty(zfAndManageUserInfoVoList)){
            zfAndManageUserInfoVoList.forEach(e-> {
                String messageContent="";
                if(Constant.STRING_1.equals(msgType)) {
                    messageContent = "【" + caseMainInfoVo.getCaseOrgName() + "】新增承办案件通知。" + e.getRealName() + "，你好。你被设置为案件" + caseMainInfoVo.getCaseNumber() + "的承办人员。请前往办案系统电脑端-案件办理-全部待办，查看明细。";
                }
                if(Constant.STRING_2.equals(msgType)) {
                    messageContent = "【" + caseMainInfoVo.getCaseOrgName() + "】移除承办案件通知。" + e.getRealName() + "，你好。你被移除案件" + caseMainInfoVo.getCaseNumber() + "的承办权限。";
                }
                //发送短信
                try {
                    SMSUtils.sendTextMessage(e.getPhone(),messageContent,"");
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
                //发送ding消息
                sendNewAdjustHandlerPersonDingMsg(caseId, caseMainInfoVo.getCaseNumber(), e.getZwdingAccountId(),msgType);

            });
        }

    }
    /**
     * 发送ding消息
     * @author liyafeng
     * @date 2022/10/20
      * @param caseId
     * @param caseNumber
     * @param zwdingAccountId
     * @return
     */
    private void sendNewAdjustHandlerPersonDingMsg(String caseId, String caseNumber, String zwdingAccountId,String msgType) {
        try {
            String dingMsgType="";
            if(Constant.STRING_1.equals(msgType)){
                dingMsgType=Constant.DING_MSG_TYPE_ADJUST_AFTER;
            }
            if(Constant.STRING_2.equals(msgType)){
                dingMsgType=Constant.DING_MSG_TYPE_ADJUST_BEFORE;
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("caseId", caseId);
            jsonObject.put("caseNumber", caseNumber);
            jsonObject.put("dingDingId", zwdingAccountId);
            jsonObject.put("dingMsgType", dingMsgType);
            BaseUtil.post(dingSendUrl, jsonObject);
        }catch (Exception e){
            System.out.println("-----------发送钉钉消息失败，caseId：{"+caseId+"}, 消息类型：{"+msgType+"}--------------");
        }
    }
    /**
     *保存附件
     * @author liyafeng
     * @date 2022/10/19
      * @param dto
     * @return {@link String}
     */
    private String saveAppendixList(HandlePersonAdjustInfoAddDto dto,UserDTO userDTO) {
        CaseMainInfoVo caseMainInfoVo=caseMainInfoMapper.selectCaseMainInfo(dto.getCaseId());
        StringBuffer attachmentId=new StringBuffer("");
        List<AppendixDto> appendixDtoList=dto.getAppendixList();
        if(!ObjectUtils.isEmpty(appendixDtoList)){
            for (AppendixDto appendixDto:appendixDtoList) {
                String id=StringUtils.uuid();
                CaseAppendixRecord caseAppendixRecord = new CaseAppendixRecord();
                caseAppendixRecord.setCaseId(dto.getCaseId());
                caseAppendixRecord.setCaseStageCode(caseMainInfoVo.getCaseCurrentStageCode());
                caseAppendixRecord.setAppendixTypeId(appendixDto.getAppendixTypeId());
                caseAppendixRecord.setAppendixUrl(appendixDto.getAppendixUrl());
                caseAppendixRecord.setAppendixName(appendixDto.getAppendixName());
                caseAppendixRecord.setCaseStageName(caseMainInfoVo.getCaseCurrentStageName());
                caseAppendixRecord.setDocumentCatalogCode("");
                caseAppendixRecord.setCaseLinkCode(caseMainInfoVo.getCaseCurrentLinkCode());
                caseAppendixRecord.setCaseLinkName(caseMainInfoVo.getCaseCurrentLinkName());
                caseAppendixRecord.setId(id);
                caseAppendixRecord.setUploadTime(LocalDateTime.now());
                caseAppendixRecord.setUploadUserId(userDTO.getUserId().toString());
                caseAppendixRecord.setUploadUserName(userDTO.getRealName());
                caseAppendixRecord.setIsDelete(Constant.STRING_0);
                caseAppendixRecord.setAppendixStatus(Constant.STRING_1);
                int num=caseAppendixRecordMapper.insert(caseAppendixRecord);
                if(StringUtils.isBlank(attachmentId)){
                    attachmentId.append(id);
                }else{
                    attachmentId.append(","+id);
                }
            }
        }
        return attachmentId.toString();
    }

    /**
     * 保存调整记录
     * @author liyafeng
     * @date 2022/10/18
      * @param dto
     * @param userDTO
     * @return {@link int}
     */
    private int saveCaseInfoAdjustRecordAndInfo(HandlePersonAdjustInfoAddDto dto,List<CaseHandlePersonInfoDto> oldCaseHandlePersonInfoList, UserDTO userDTO,String attachmentId) {
        int num=0;
        StringBuffer itemCodeBeforeAdjust = new StringBuffer("");
        StringBuffer itemCodeAfterAdjust = new StringBuffer("");
        StringBuffer itemShowInfoBeforeAdjust = new StringBuffer("");
        StringBuffer itemShowInfoAfterAdjust = new StringBuffer("");
        List<CaseHandlePersonInfoDto> afterHandlePersonInfoList =dto.getAfterHandlePersonInfoList();
        if(!ObjectUtils.isEmpty(oldCaseHandlePersonInfoList)) {
            oldCaseHandlePersonInfoList.forEach(e -> {
               if(StringUtils.isBlank(itemCodeBeforeAdjust)){
                   itemCodeBeforeAdjust.append(e.getHandlePersonId());
                   itemShowInfoBeforeAdjust.append("主办:"+e.getHandlePersonName()+"("+e.getHandleDeptName()+")");
               }else{
                   itemCodeBeforeAdjust.append(","+e.getHandlePersonId());
                   itemShowInfoBeforeAdjust.append("协办:"+e.getHandlePersonName()+"("+e.getHandleDeptName()+")");
               }
            });
        }
        if(!ObjectUtils.isEmpty(dto.getAfterHandlePersonInfoList())) {
            afterHandlePersonInfoList.forEach(e -> {
                if(StringUtils.isBlank(itemCodeAfterAdjust)){
                    itemCodeAfterAdjust.append(e.getHandlePersonId());
                    itemShowInfoAfterAdjust.append("主办:"+e.getHandlePersonName()+"("+e.getHandleDeptName()+")");
                }else{
                    itemCodeAfterAdjust.append(","+e.getHandlePersonId());
                    itemShowInfoAfterAdjust.append("协办:"+e.getHandlePersonName()+"("+e.getHandleDeptName()+")");
                }
            });
        }
        //新增调整记录
        String recordId=StringUtils.uuid();
        CaseInfoAdjustRecord caseInfoAdjustRecord=new CaseInfoAdjustRecord();
        caseInfoAdjustRecord.setId(recordId);
        caseInfoAdjustRecord.setCaseId(dto.getCaseId());
        caseInfoAdjustRecord.setAdjustType(Constant.STRING_3);
        caseInfoAdjustRecord.setItemCodeBeforeAdjust(itemCodeBeforeAdjust.toString());
        caseInfoAdjustRecord.setItemCodeAfterAdjust(itemCodeAfterAdjust.toString());
        caseInfoAdjustRecord.setItemShowInfoBeforeAdjust(itemShowInfoBeforeAdjust.toString());
        caseInfoAdjustRecord.setItemShowInfoAfterAdjust(itemShowInfoAfterAdjust.toString());
        caseInfoAdjustRecord.setAdjustReason(dto.getAdjustReason());
        caseInfoAdjustRecord.setAttachmentId(attachmentId);
        caseInfoAdjustRecord.setAdjustUserId(userDTO.getUserId().toString());
        caseInfoAdjustRecord.setAdjustUserName(userDTO.getRealName());
        caseInfoAdjustRecord.setAdjustTime(LocalDateTime.now());
        caseInfoAdjustRecord.setAdjustOrgCode(userDTO.getOrgCode());
        caseInfoAdjustRecord.setAdjustOrgName(userDTO.getOrgName());
        caseInfoAdjustRecord.setAdjustReasonType(dto.getAdjustReasonType());
        num=caseInfoAdjustRecordMapper.insert(caseInfoAdjustRecord);
        //新增调整信息
        CaseHandlePersonAdjustInfo caseHandlePersonAdjustInfo=new CaseHandlePersonAdjustInfo();
        caseHandlePersonAdjustInfo.setId(StringUtils.uuid());
        caseHandlePersonAdjustInfo.setCaseId(dto.getCaseId());
        if(!ObjectUtils.isEmpty(afterHandlePersonInfoList)) {
            caseHandlePersonAdjustInfo.setAdjustAfterHandlerName(afterHandlePersonInfoList.get(0).getHandlePersonName()+","+afterHandlePersonInfoList.get(1).getHandlePersonName());
            caseHandlePersonAdjustInfo.setAdjustAfterDeptName(afterHandlePersonInfoList.get(0).getHandleDeptName());
        }
        if(!ObjectUtils.isEmpty(oldCaseHandlePersonInfoList)) {
            caseHandlePersonAdjustInfo.setAdjustBeforeHandlerName(oldCaseHandlePersonInfoList.get(0).getHandlePersonName()+","+oldCaseHandlePersonInfoList.get(1).getHandlePersonName());
            caseHandlePersonAdjustInfo.setAdjustBeforeDeptName(oldCaseHandlePersonInfoList.get(0).getHandleDeptName());
        }
        caseHandlePersonAdjustInfo.setRecordId(recordId);
        caseHandlePersonAdjustInfo.setAdjustUserId(userDTO.getUserId().toString());
        caseHandlePersonAdjustInfo.setAdjustUserName(userDTO.getRealName());
        caseHandlePersonAdjustInfo.setAdjustTime(new Date());
        caseHandlePersonAdjustInfo.setAdjustDeptCode(userDTO.getDeptCode());
        caseHandlePersonAdjustInfo.setAdjustDeptName(userDTO.getDeptName());
        caseHandlePersonAdjustInfo.setAdjustOrgCode(userDTO.getOrgCode());
        caseHandlePersonAdjustInfo.setAdjustOrgName(userDTO.getOrgName());
        caseHandlePersonAdjustInfo.setAdjustPhone(userDTO.getPhone());
        caseHandlePersonAdjustInfo.setAdjustAfterHandlerId(itemCodeAfterAdjust.toString());
        caseHandlePersonAdjustInfo.setAdjustBeforeHandlerId(itemCodeBeforeAdjust.toString());
        caseHandlePersonAdjustInfoMapper.insert(caseHandlePersonAdjustInfo);
        return num;
    }

    private void dealCaseRegisterHandlePersonInfo(List<CaseHandlePersonInfoDto> caseHandlePersonInfoDtoList, String caseId, UserDTO userInfo) {
        for (CaseHandlePersonInfoDto handlePersonInfoDto : caseHandlePersonInfoDtoList) {
            CaseHandlePersonRecord caseHandlePersonRecord = new CaseHandlePersonRecord();
            BeanUtils.copyProperties(handlePersonInfoDto, caseHandlePersonRecord);
            caseHandlePersonRecord.setHandlePersonType(handlePersonInfoDto.getHandlePersonType());
            caseHandlePersonRecord.setDingId(handlePersonInfoDto.getDingId());
            if (ObjectUtil.isNotEmpty(handlePersonInfoDto.getHandlePersonId())) {
                if (ObjectUtil.isEmpty(xzzfInterfaceService.getLawEnforcementCertWithUserId(handlePersonInfoDto.getHandlePersonId()))) {
                    throw new BusinessException("办案人员" + handlePersonInfoDto.getHandlePersonName() + "的执法证为空!");
                }
                caseHandlePersonRecord.setLawEnforcementCert(xzzfInterfaceService.getLawEnforcementCertWithUserId(handlePersonInfoDto.getHandlePersonId()));
            }
            //  签名校验
            String handlePersonSignPic = null;
            try {
                handlePersonSignPic = commonService.getHandleSignData(handlePersonInfoDto.getHandlePersonId());
            } catch (Exception e) {
                e.printStackTrace();
                if ("true".equals(isCheckHandleSign)) {
                    if (ObjectUtil.isEmpty(handlePersonSignPic)) {
                        throw new BusinessException("因未获取承办人员" + handlePersonInfoDto.getHandlePersonName() + "有效签名信息，无法提交");
                    }
                }
            }
            caseHandlePersonRecord.setHandleSignPic(handlePersonSignPic);
            caseHandlePersonRecord.setId(BaseUtil.createUid());
            caseHandlePersonRecord.setCaseId(caseId);
            caseHandlePersonRecord.setHandleOrgCode(userInfo.getOrgCode());
            caseHandlePersonRecord.setHandleOrgName(userInfo.getOrgName());
            caseHandlePersonRecord.setHandleOrgTel(userInfo.getTelPhone());
            caseHandlePersonRecord.setHandleDeptCode(userInfo.getDeptCode());
            caseHandlePersonRecord.setHandleDeptName(userInfo.getDeptName());
            caseHandlePersonRecord.setHandleDeptTel(userInfo.getTelPhone());
            caseHandlePersonRecord.setHandlePersonTel(handlePersonInfoDto.getHandlePersonTel());
            caseHandlePersonRecord.setAddTime(new Date());
            caseHandlePersonRecord.setStatus(Constant.STRING_1);
            caseHandlePersonRecordMapper.insertSelective(caseHandlePersonRecord);
        }

    }
}
